<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use util\Excel;

use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;

/**
 * Exchange控制器
 */
class Exchange extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\Exchange();

        // $this->validate = \app\admin\validate\Exchange::class;
    }
    /**
     * 列表
     */
    public function index()
    {

        list($limit, $where, $sortArr) = $this->buildTableParames();

        $list = $this->model
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $lists[$k]['createtime'] = date('Y-m', strtotime($v['create_time']));
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];

        return json($data);
    }
    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_exchage($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入汇率
    public function  import_exchage($url)
    {
        //获取导入的数据
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1], 2);
        $excle_data = array_values($data[0]);
        $date = date('Y-m', strtotime('-1 month'));
        // 查询上月的汇率
        if (!empty($last_translate)) {
            table('exchange')->where(['create_time' => $date])->delete();
        }
        foreach ($excle_data as $k => $v) {
            $insert_data = [
                'site' => $v[0],
                'exchange' => $v[1],
                'create_time' => $date
            ];
            $this->model->insert($insert_data);
        }
        return success('导入成功');
    }
}
